<template>
  <div class="sensor-container">
    <div class="header">
      <h2>传感器管理</h2>
      <el-button type="primary" @click="handleAdd">新增传感器</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="所属家庭">
          <el-select 
            v-model="searchForm.family_id" 
            placeholder="请选择家庭"
            clearable
            @change="handleFamilyChange"
            @clear="handleFamilyClear"
            class="search-select"
          >
            <el-option
              v-for="item in familyList"
              :key="item.family_id"
              :label="item.family_name"
              :value="item.family_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属房间">
          <el-select 
            v-model="searchForm.room_id" 
            placeholder="请选择房间"
            clearable
            @clear="handleSearch"
            :disabled="!searchForm.family_id"
            class="search-select"
          >
            <el-option
              v-for="item in filteredRoomList"
              :key="item.room_id"
              :label="item.room_name"
              :value="item.room_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="传感器名称">
          <el-select 
            v-model="searchForm.site_name" 
            placeholder="请选择传感器"
            clearable
            @clear="handleSearch"
            class="search-select"
          >
            <el-option
              v-for="item in siteNameList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="请选择状态"
            clearable
            @clear="handleSearch"
            class="search-select"
          >
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table :data="siteList" style="width: 100%" v-loading="loading" border stripe>
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="site_name" label="传感器名称" />
      <el-table-column prop="device_model" label="设备型号" />
      <el-table-column label="所属房间" width="180">
        <template #default="{ row }">
          {{ getLocationName(row.room_id) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 'online' ? 'success' : 'danger'">
            {{ row.status === 'online' ? '在线' : '离线' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="installed_at" label="安装时间" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增传感器' : '编辑传感器'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="所属家庭" prop="family_id">
          <el-select 
            v-model="formData.family_id" 
            placeholder="请选择家庭"
            @change="handleDialogFamilyChange"
          >
            <el-option
              v-for="item in familyList"
              :key="item.family_id"
              :label="item.family_name"
              :value="item.family_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属房间" prop="room_id">
          <el-select 
            v-model="formData.room_id" 
            placeholder="请选择房间"
            :disabled="!formData.family_id"
          >
            <el-option
              v-for="item in dialogRoomList"
              :key="item.room_id"
              :label="item.room_name"
              :value="item.room_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="传感器名称" prop="site_name">
          <el-input v-model="formData.site_name" />
        </el-form-item>
        <el-form-item label="设备型号" prop="device_model">
          <el-input v-model="formData.device_model" />
        </el-form-item>
        <el-form-item label="安装时间" prop="installed_at" v-if="dialogType === 'add'">
          <el-date-picker
            v-model="formData.installed_at"
            type="datetime"
            placeholder="请选择安装时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDT[HH:mm:ss]"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getSiteList,
  addSite,
  updateSite,
  deleteSite
} from '@/api/site'
import { getRoomList } from '@/api/room'
import { getFamilyList } from '@/api/family'

// 数据列表
const siteList = ref([])
const roomList = ref([])
const familyList = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const formData = ref({
  site_name: '',
  device_model: '',
  room_id: '',
  installed_at: ''
})

// 表单校验规则
const rules = {
  site_name: [{ required: true, message: '请输入传感器名称', trigger: 'blur' }],
  device_model: [{ required: true, message: '请选择设备型号', trigger: 'change' }],
  room_id: [{ required: true, message: '请选择所属房间', trigger: 'change' }],
  installed_at: [{ required: true, message: '请选择安装时间', trigger: 'change' }]
}

// 搜索表单
const searchForm = ref({
  family_id: '',
  room_id: '',
  site_name: '',
  status: ''
})

// 过滤后的房间列表（根据选择的家庭筛选）
const filteredRoomList = computed(() => {
  if (!searchForm.value.family_id) return []
  return roomList.value.filter(room => room.family_id === searchForm.value.family_id)
})

// 对话框中的房间列表
const dialogRoomList = ref([])

// 传感器名称列表（用于下拉选择）
const siteNameList = computed(() => {
  return [...new Set(siteList.value.map(site => site.site_name))]
})

// 家庭变更处理
const handleFamilyChange = async (familyId) => {
  searchForm.value.room_id = '' // 清空房间选择
  if (familyId) {
    // 获取该家庭的房间列表
    try {
      const res = await getRoomList()
      roomList.value = res.data.filter(room => room.family_id === familyId)
    } catch (error) {
      console.error('获取房间列表失败:', error)
    }
  }
}

// 家庭清空处理
const handleFamilyClear = () => {
  searchForm.value.family_id = ''
  searchForm.value.room_id = ''
  roomList.value = []
  handleSearch()
}

// 对话框中家庭变更处理
const handleDialogFamilyChange = async (familyId) => {
  formData.value.room_id = '' // 清空房间选择
  if (familyId) {
    try {
      const res = await getRoomList()
      dialogRoomList.value = res.data.filter(room => room.family_id === familyId)
    } catch (error) {
      console.error('获取房间列表失败:', error)
    }
  }
}

// 获取完整位置名称的方法（家庭-房间）
const getLocationName = (roomId) => {
  const room = roomList.value.find(r => r.room_id === roomId)
  if (!room) return '未知位置'
  
  const family = familyList.value.find(f => f.family_id === room.family_id)
  if (!family) return `未知家庭-${room.room_name}`
  
  return `${family.family_name}-${room.room_name}`
}

// 获取传感器列表
const getList = async () => {
  try {
    loading.value = true
    const res = await getSiteList()
    // 根据搜索条件过滤数据
    let filteredData = res.data
    
    if (searchForm.value.site_name) {
      filteredData = filteredData.filter(item => 
        item.site_name.toLowerCase().includes(searchForm.value.site_name.toLowerCase())
      )
    }
    
    if (searchForm.value.room_id) {
      filteredData = filteredData.filter(item => 
        item.room_id === searchForm.value.room_id
      )
    }
    
    if (searchForm.value.status) {
      filteredData = filteredData.filter(item => 
        item.status === searchForm.value.status
      )
    }
    
    siteList.value = filteredData
  } catch (error) {
    console.error('获取传感器列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = 'add'
  formData.value = {
    site_name: '',
    device_model: '',
    room_id: '',
    installed_at: ''
  }
  dialogVisible.value = true
}

// 编辑按钮点击
const handleEdit = (row) => {
  dialogType.value = 'edit'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 删除按钮点击
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该传感器吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSite(row.site_id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addSite(formData.value)
          ElMessage.success('添加成功')
        } else {
          await updateSite(formData.value)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('操作失败:', error)
      }
    }
  })
}

// 查询按钮点击
const handleSearch = () => {
  getList()
}

// 重置按钮点击
const handleReset = () => {
  searchForm.value = {
    family_id: '',
    room_id: '',
    site_name: '',
    status: ''
  }
  getList()
}

// 初始化数据
const initData = async () => {
  try {
    // 获取家庭列表
    const familyRes = await getFamilyList()
    familyList.value = familyRes.data
    
    // 获取所有房间列表
    const roomRes = await getRoomList()
    roomList.value = roomRes.data
    
    // 获取传感器列表
    await getList()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  initData()
})
</script>

<style scoped>
.sensor-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 调整表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 15px;
  margin-right: 15px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 统一下拉选择框宽度和样式 */
:deep(.search-select) {
  width: 200px;
}

:deep(.search-select .el-input__inner) {
  height: 32px;
  line-height: 32px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
}

/* 统一输入框宽度和样式 */
:deep(.search-input) {
  width: 200px;
}

:deep(.search-input .el-input__inner) {
  height: 32px;
  line-height: 32px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
}

/* 按钮组样式 */
.search-buttons {
  margin-left: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 确保下拉选项文字可见 */
:deep(.el-select-dropdown__item) {
  padding: 0 20px;
  color: #606266;
}

:deep(.el-select-dropdown__item.selected) {
  color: #409EFF;
  font-weight: 700;
}

/* 优化表单布局 */
:deep(.el-form--inline) {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: flex-start;
}

/* 调整表单项间距 */
:deep(.el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

/* 确保选择框内容完整显示 */
:deep(.el-select__tags) {
  max-width: calc(100% - 30px);
}
</style> 